// Copyright 2022 Espressif Systems (Shanghai) Co. Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdint.h>
#include <string.h>

#include "url_handlers.h"


/* Handler to redirect incoming GET request for /index.html to /
 * This can be overridden by uploading file with same name */
static esp_err_t index_html_get_handler(httpd_req_t *req)
{
    extern const char html_start[] asm("_binary_index_html_start");
    extern const char html_end[]   asm("_binary_index_html_end");
    const size_t html_size = (html_end - html_start);
    httpd_resp_set_type(req, "text/html");
    /* Add file upload form and script which on execution sends a POST request to /upload */
    httpd_resp_send_chunk(req, (const char*) html_start, html_size);
    /* Respond with an empty chunk to signal HTTP response completion */
    return httpd_resp_send_chunk(req, NULL, 0);
}

/* Handler to respond with an icon file embedded in flash.
 * Browsers expect to GET website icon at URI /favicon.ico.
 * This can be overridden by uploading file with same name */
static esp_err_t favicon_get_handler(httpd_req_t *req)
{
    extern const unsigned char favicon_ico_start[] asm("_binary_favicon_ico_start");
    extern const unsigned char favicon_ico_end[]   asm("_binary_favicon_ico_end");
    const size_t favicon_ico_size = (favicon_ico_end - favicon_ico_start);
    httpd_resp_set_type(req, "image/x-icon");
    httpd_resp_send(req, (const char *)favicon_ico_start, favicon_ico_size);
    return ESP_OK;
}

/* Handler to respond with CSS.
 * Browsers expect to GET website icon at URI /stylesheet.css.*/
static esp_err_t css_get_handler(httpd_req_t *req)
{
    extern const unsigned char css_start[] asm("_binary_stylesheet_css_start");
    extern const unsigned char css_end[]   asm("_binary_stylesheet_css_end");
    const size_t css_size = (css_end - css_start);
    httpd_resp_set_type(req, "text/css");
    httpd_resp_send(req, (const char *)css_start, css_size);
    return ESP_OK;
}

httpd_uri_t httpd_uri_array[URL_HANDLERS_MAX] = {
    {"/", HTTP_GET, index_html_get_handler, NULL},
    {"/favicon.ico", HTTP_GET, favicon_get_handler, NULL},
    {"/stylesheet.css", HTTP_GET, css_get_handler, NULL},
};
